using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Volo.Abp.AspNetCore.Mvc;
using TenantManagementService.Monitoring;

namespace TenantManagementService.Controllers
{
    /// <summary>
    /// Prometheus 指标端点控制器
    /// </summary>
    [ApiController]
    [Route("metrics")]
    [IgnoreAntiforgeryToken] // Prometheus 拉取不需要 CSRF 保护
    public class PrometheusController : AbpControllerBase
    {
        private readonly PrometheusMetricsService _prometheusMetricsService;
        private readonly ILogger<PrometheusController> _logger;

        public PrometheusController(
            PrometheusMetricsService prometheusMetricsService,
            ILogger<PrometheusController> logger)
        {
            _prometheusMetricsService = prometheusMetricsService;
            _logger = logger;
        }

        /// <summary>
        /// 获取 Prometheus 格式的指标
        /// </summary>
        [HttpGet("")]
        [HttpGet("prometheus")]
        public IActionResult GetMetrics()
        {
            try
            {
                var metricsText = _prometheusMetricsService.GeneratePrometheusMetricsText();

                _logger.LogDebug("Prometheus 指标请求已处理");

                return Content(metricsText, "text/plain; version=0.0.4; charset=utf-8");
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "获取 Prometheus 指标失败");
                return StatusCode(500, "Internal Server Error");
            }
        }

        /// <summary>
        /// 获取指标统计信息
        /// </summary>
        [HttpGet("statistics")]
        public IActionResult GetStatistics()
        {
            try
            {
                var statistics = _prometheusMetricsService.GetStatistics();

                return Ok(new
                {
                    success = true,
                    data = statistics
                });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "获取指标统计信息失败");
                return StatusCode(500, new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 健康检查端点（用于 Prometheus Blackbox Exporter）
        /// </summary>
        [HttpGet("health")]
        public IActionResult HealthCheck()
        {
            // 检查服务健康状态
            var isHealthy = true; // 实际项目中应该检查各种依赖项

            _logger.LogDebug("Prometheus 健康检查请求已处理");

            return isHealthy ? Ok(new { status = "healthy" }) :
                                StatusCode(503, new { status = "unhealthy" });
        }

        /// <summary>
        /// 指标重置端点（用于测试或维护）
        /// </summary>
        [HttpPost("reset")]
        public IActionResult ResetMetrics([FromBody] ResetMetricsRequest request)
        {
            try
            {
                if (request.ResetAll)
                {
                    _prometheusMetricsService.ClearAllMetrics();
                    _logger.LogInformation("所有 Prometheus 指标已重置");

                    return Ok(new { success = true, message = "所有指标已重置" });
                }
                else if (!string.IsNullOrEmpty(request.MetricName))
                {
                    _prometheusMetricsService.ResetMetric(request.MetricName, request.Labels);
                    _logger.LogInformation("指标 {MetricName} 已重置", request.MetricName);

                    return Ok(new { success = true, message = $"指标 {request.MetricName} 已重置" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "请指定 metricName 或设置 resetAll 为 true" });
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "重置指标失败");
                return StatusCode(500, new { success = false, message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 重置指标请求
    /// </summary>
    public class ResetMetricsRequest
    {
        /// <summary>
        /// 是否重置所有指标
        /// </summary>
        public bool ResetAll { get; set; }

        /// <summary>
        /// 指标名称（ResetAll 为 false 时使用）
        /// </summary>
        public string? MetricName { get; set; }

        /// <summary>
        /// 指标标签（可选）
        /// </summary>
        public Dictionary<string, string>? Labels { get; set; }
    }
}